<?php
require_once dirname(__FILE__) . '/../includes/common.inc.php';
require_once dirname(__FILE__) . '/../includes/pdoorm.inc.php';

header('Content-Type: text/plain');

if (isset($_COOKIE[OPERATOR])) { 
 $coperator = json_decode($_COOKIE[OPERATOR]);
}

try {
  $action = MiscUtils::getParam('action', 'v1myorder');
  $condition = MiscUtils::getParam('c', 'where  1 = 1');
  $e_oid = MiscUtils::getParam('oid', NULL);

  
  /*echo $action."\n";
  echo $condition."\n";
  echo $e_oid."\n";
  echo $sql."\n";
  die;*/
  
    switch($action){
        case'v1customer':
            customerfind($action,$condition,$e_oid);
            break;  

        case'v2customer':
        	{
            $action='v1customer';
            customerfind($action,$condition,$e_oid,'p');
            
        	}
            break;  
                       
            
        case'v1myorder':
            myorderfind('v1myorder',$condition,$e_oid);
        	break;
        case'v1sample':
            samplefind($action,$condition,$e_oid);
            break;
        case'v1sample_s':
            {
             $action = 'v1sample';
             samplefind($action,$condition,$e_oid,'s');
            }
           break;   
        case'v1package':
            packagefind($action,$condition,$e_oid);
            break;  
        case'v1package_s':
            {
             $action = 'v1package';
             packagefind($action,$condition,$e_oid,'s');
            }
           break;
           
        case'v1packageitem':
        case'v1packageitem_s':	
            {
                packageitemfind($action,$condition,$e_oid);  
            }
            break;      
                
        case'v1purchaseitem_s':   
        case'v1purchaseitem':
        case'v1purchaseitem_o': 	
            {
                purchaseitemfind($action,$condition,$e_oid);  
            }
            break;
            
        case'h1purchase':   
            {
            	$action = 'h1myorder';
                h1purchaseitemfind($action,$condition,$e_oid);  
            }
            break;
            
        case'findByRequest':
        	{
        		findByRequest($action,$condition,$e_oid);
        	}
        	break;
        	
        case'cuspayment':
        	{
        		cuspayment($action,$condition,$e_oid);
        	}
        	break;                                
            
        default:
             pdofind($action,$condition,$e_oid);
            break;  
        
    }

   
} catch (PDOException $e) {
  echo $e->getMessage();
}


/**
 *function list  
 *2011年8月2日 14:11:59 ns.lanbinbin 
 *$out_method输出的方式，为空默认json_encode($result)输出，不为空返回$result->data[0] 数组
**/

function pdofind($action,$condition,$e_oid,$out_method=''){

     if (strpos($condition,'where') === false)
     {
         $condition = "where ".$condition;
     }
     
    switch($action)
    {
        case'expense':
            $condition .= ($e_oid) ? ' AND d.payee = '. $e_oid .'': '';
            break;  
            
        case'v1purchaseitem':
            $condition .= ($e_oid) ? ' AND d.sampleId = \'' . $e_oid . '\'' : '';
            break;
        case'v1myorder_p':
            {
              $condition .= ($e_oid) ? ' AND d.trackId = \'' . $e_oid . '\'' : ''; //handledialogssignee 
              $action = 'v1myorder';
            }
            
            break;           
        case'v1user_p':
            {
              //$condition .= ($e_oid) ? ' AND d.pEnabled = \'' . $e_oid . '\'' : ''; //handledialogssignee
              $action = 'v1user';  
            }
            break;
        case'ocontract':
            {
              $condition .= ($e_oid) ? ' AND d.orderType = \'' . $e_oid . '\'' : ''; //handledialogssignee
              $action = 'contract';  
            }
            break;
            
           default:
            $condition .= ($e_oid) ? ' AND d.e_oid = \'' . $e_oid . '\'' : '';          
            break;       
     
    }
    
    
    switch($action)
    {
        case'ireception':
        case'isource':
        case'iceremony':
        case'iculture':
        case'ipayee':
        case'iparticular':
	
            $orderby = 'order by d.name';
            break;  

        case'v1user':
        case'v1user_p': 
        	            
            $orderby = 'order by d.account';
            break;
                       
        default:
            $orderby = '';          
            break;       
     
    }   
    

  
  
  $result = new stdClass();
  $result->data = array();

  
    if($action=='iceremony' || $action=='ireception')
    {
      $sql2 = "SELECT min(d.e_oid)AS id,d.trackId,d.name FROM ns_".$action." as d  $condition  GROUP BY d.name; $orderby";  	
    }else{
      $sql2 = "SELECT d.e_oid as id, d.* FROM ns_".$action." as d  $condition  $orderby";
   // echo $sql2;
    }
    
    $tmp=getall($sql2);

    
    foreach($tmp as $tmp2){
        
        switch($action){
            case'datezone':
                {
                    $tmp2->start = SimpleDate::fromStamp($tmp2->start);
                    $tmp2->end = SimpleDate::fromStamp($tmp2->end);
                }
                break;
                
            default:
                break;  
        }
        
        $result->data[] = $tmp2;
    }
    
    
    if(!empty($out_method)){
        return $result->data[0];   
    }else{
        echo json_encode($result);
    }    
    
}

/*2011年8月8日 10:04:27
 * $action表名,$condition条件,
 * $e_oid自增编号,
 * $flag=''为空只读取父表数据，s读取所有子表数据
 * $out_method输出的方式，为空默认json_encode($result)输出，不为空返回$result->data[0] 数组
 * */
 function samplefind($action,$condition,$e_oid,$flag='',$out_method=''){

  $condition .= ($e_oid) ? ' AND u.e_oid = \'' . $e_oid . '\'' : '';
  
  
  $result = new stdClass();
  $result->data = array(); 
  
  
    $sql2 = "SELECT u.e_oid as id, u.* FROM ns_".$action." as u $condition";
    
    $tmp=getall($sql2);
    
   
    if(!empty($e_oid) || !empty($flag)){
       if(!empty($tmp))
       {
    	foreach($tmp as $tmp2){
            $tmp2->attributes = array();
            
            $tmp21 = getsonall('ns_v1sampleattribute','sample_id',$tmp2->id);
            
            $tmp2->attributes = $tmp21;
            
            foreach($tmp21 as $v21){
              $tmp211 = getsonall('ns_v1sampleattributeoption','sampleattribute_id',$v21->e_oid,'','e_oid asc');
              
              //print_r($tmp211);
              
              $v21->options =  array();
              
              $v21->options =$tmp211;
            }
            
            
            $result->data[] = $tmp2;
          }
       }
    }else{
    	 if(!empty($tmp)) 
    	 {
            foreach($tmp as $tmp2){
            $result->data[] = $tmp2;
            }       
          }
    }
    
    if(!empty($out_method)){
    	if(!empty($tmp)){
    		return $result->data[0];
    	}else{
            return false;
    	}   
    }else{
        echo json_encode($result);
    }
    
 }
 
 
 function packagefind($action,$condition,$e_oid,$flag=''){

  $condition .= ($e_oid) ? ' AND u.e_oid = \'' . $e_oid . '\'' : '';
  
  
  $result = new stdClass();
  $result->data = array(); 
  
  
    $sql2 = "SELECT u.e_oid as id, u.* FROM ns_".$action." as u $condition";
    
    $tmp=getall($sql2);
    
   
    if(!empty($e_oid) || !empty($flag)){
        foreach($tmp as $tmp2){
            $tmp2->packageItems = array();
            
            $tmp21 = getsonall('ns_v1packageitem','package_id',$tmp2->id);
            
            $tmp2->packageItems = $tmp21;
            
            foreach($tmp21 as $v21){
              //读取sample
              $v21->sample = array();
              $samplearr = samplefind('v1sample','where 1=1',$v21->sample_id,'s','g');
              if(!empty($samplearr))
              {
                $v21->sample = $samplearr;
              }    
                
              $tmp211 = getsonall('ns_v1packageitemselect','packageitem_id',$v21->e_oid);
              $v21->selects =  array();
              
              $v21->selects =$tmp211;
            }
            
            
            $result->data[] = $tmp2;
        }
    }else{
            foreach($tmp as $tmp2){
            $result->data[] = $tmp2;
        }       
    }
  echo json_encode($result);   
    
    
 }


/*
 *packageitemfind
 */ 
    function packageitemfind($action,$condition,$e_oid,$flag='')
    {
          if($action == 'v1packageitem_s')
          {
              
              $condition .= ($e_oid) ? ' AND u.sample_id = \'' . $e_oid . '\'' : '';
              $action = 'v1packageitem';
          }else{
              $condition .= ($e_oid) ? ' AND u.e_oid = \'' . $e_oid . '\'' : '';
          }
          
          
          $result = new stdClass();
          $result->data = array(); 
          
          
            $sql2 = "SELECT u.e_oid as id, u.* FROM ns_".$action." as u $condition";
            
            $tmp=getall($sql2);
            
           
            if(!empty($e_oid) || !empty($flag)){
                foreach($tmp as $tmp2)
                {
                
                    $tmp211 = getsonall('ns_v1packageitemselect','packageitem_id',$tmp2->e_oid);
                    $tmp2->selects =  array();
                      
                    $tmp2->selects =$tmp211;
                    
                    $result->data[] = $tmp2;
                }
            }else{
                    foreach($tmp as $tmp2){
                    $result->data[] = $tmp2;
                }       
            }
          echo json_encode($result);                  
    
    
    
    }  


/*
   purchaseitemfind

 */  
    function purchaseitemfind($action,$condition,$e_oid,$flag='')
    {
          /*if($action == 'v1purchaseitem_s')
          {
            
            $condition .= ($e_oid) ? ' AND u.sampleId = \'' . $e_oid . '\'' : '';
            $action = 'v1purchaseitem';
          }else{
            $condition .= ($e_oid) ? ' AND u.e_oid = \'' . $e_oid . '\'' : ''; 
          }*/
	    	switch($action)
	    	{
	    		case'v1purchaseitem_s':
	    			{
			            $condition .= ($e_oid) ? ' AND u.sampleId = \'' . $e_oid . '\'' : '';
			            $action = 'v1purchaseitem';    				
	    			}
	    			break;
	
	            case'v1purchaseitem_o':
	                {
	                	$ordid = MiscUtils::getParam('orid', NULL);
	                    $condition .= ($e_oid) ? ' AND u.otherId = \'' . $e_oid . '\'' : '';
	                    $condition .= ($ordid) ? ' AND u.order_id = \'' . $ordid . '\'' : '';
	                    $condition .= ' AND u.cancelled = 0 ';
	                    $action = 'v1purchaseitem';                 
	                }
	                break;    			
	    			
	    		default:
	    			{
	    				$condition .= ($e_oid) ? ' AND u.e_oid = \'' . $e_oid . '\'' : ''; 
	    			}
	    			break;
	    				
	    	}
          
          
          
          
          $result = new stdClass();
          $result->data = array(); 
          
          
            $sql2 = "SELECT u.e_oid as id, u.* FROM ns_".$action." as u $condition";
            
            $tmp=getall($sql2);
            
           
            if(!empty($e_oid) || !empty($flag)){
                foreach($tmp as $tmp2)
                {
                    $tmp211 = getsonall('ns_v1purchaseitemselect','purchaseitem_id',$tmp2->e_oid);
                    $tmp2->selects =  array();
                      
                    $tmp2->selects =$tmp211;
                    
                    $tmpnote = getsonall('ns_v1purchasenote','purchaseitem_id',$tmp2->e_oid);
                    $tmp2->notes =  array();
                      
                    $tmp2->notes =$tmpnote;                 
                    
                    
                    $result->data[] = $tmp2;
                }
            }else{
                    foreach($tmp as $tmp2){
                    $result->data[] = $tmp2;
                }       
            }
          echo json_encode($result);        
    
    
    
    }   
 
 
 /*
  * customer 
  * 
  */
 function customerfind($action,$condition,$e_oid,$flag=''){
    
  $condition = MiscUtils::getParam('c', 'where 1 = 1'); 
  
  $order = MiscUtils::getParam('o', 'c.e_oid');
  $queue = MiscUtils::getParam('q', 'DESC');
  $page = MiscUtils::getParam('p', START);
  $size = MiscUtils::getParam('s', NULL); 
  $cond = MiscUtils::getParam('cond', '0'); 
  $date = MiscUtils::getParam('date', ''); 
  $from = MiscUtils::getParam('from', ''); 
  $to = MiscUtils::getParam('to', ''); 
  $pageSkip = ($page - 1) * $size;
  
  if($date){
	  $dateobj = json_decode($date);
	  
	  $date2 = $dateobj;
	  
	  $date2->hours = 23;
	  $date2->minutes = 59;
	  $date2->seconds = 59;
	  
	  $wd1 = SimpleDate::toStamp(json_decode($date));
	  $wd2 = SimpleDate::toStamp($date2);
  }
   
  $condition .= ($e_oid) ? ' AND c.e_oid = \'' . $e_oid . '\'' : '';
  $condition .= ($date) ? ' AND o.date >= \'' . $wd1 . '\' AND o.date <= \'' . $wd2 . '\'' : '';
  $condition .= ($from) ? ' AND (c.createdDate >= \'' . SimpleDate::toStamp(json_decode($from)) . '\')' : '';
  $condition .= ($to) ? ' AND (c.createdDate <= \'' . SimpleDate::toStamp(json_decode($to)) . '\')' : '';
  
   if ($cond == 1) {
    $condition .= ' AND 1=1';
  } else {
    $condition .= ' AND c.cancelled = 0';
  }  
  
  $result = new stdClass();
  $result->data = array(); 
  $result->page = $page;
  $result->size = $size;
  $result->order = $order;
  $result->queue = $queue;
  $result->condition = $condition;    

  
  
  
    $sql2 = "SELECT DISTINCT c.e_oid as id, c.* FROM ns_".$action." as c $condition ";
    //echo $sql2;
    $result->total = count_num($sql2);
    
    
    
    $sql2 .=  (($order && $queue) ? " ORDER BY $order $queue " : '') . (($page && $size) ? " LIMIT " . $pageSkip . ", $size" : '');
    
    
    $tmp=getall($sql2);
    
    
        foreach($tmp as $tmp2){
            
            //get officenote
            $tmp2->onote =array();
            $tmponote = getsonall('ns_v1officenote','customerId',$tmp2->id);
            $tmp2->onote = $tmponote; 
			

            $tmp2->email =array();
            $tmpemail = getsonall('ns_emailhistory','customerid',$tmp2->id);
            $tmp2->email = $tmpemail; 			

            
        	//get orders
            $tmp2->orders =array();
            
            $tmporder = getsonall('ns_v1myorder','customerId',$tmp2->id);
            
            
            $tmp2->orders = $tmporder; 
            
            
            
            
            foreach($tmporder as $order){
              //get purchaseitem
              $order->purchaseItems = array();
              $pitem = getsonall('ns_v1purchaseitem','order_id',$order->e_oid);
              
               foreach($pitem as $pis){
                 $pis->selects = array();//selects
                 $pis->notes =array();//notes
                 
                 $selectarr = getsonall('ns_v1purchaseitemselect','purchaseitem_id',$pis->e_oid);
                 $notearr = getsonall('ns_v1purchasenote','purchaseitem_id',$pis->e_oid);
                 
                 foreach($selectarr as $select){
                    $pis->selects[] = $select;  
                    
                 }
                 
                 foreach($notearr as $notes){
                   $pis->notes[] = $notes;  
                    
                 }
                 
                 
                 $order->purchaseItems[] = $pis;
                             
                 
               }//end purchaseitem
               
              $order->payments = array();
              $payment = getsonall('ns_v1payment','orderId',$order->e_oid); 
              $order->payments = $payment;
              
            if(!empty($flag)){  
              $sqlpaym="SELECT SUM(amount) AS amount,orderId,customerId,`date`,stage,cancelled FROM ns_v1payment WHERE orderId=".$order->e_oid." GROUP BY trackId,orderId";
              $paytmp=getall($sqlpaym);
              $order->pays = $paytmp;
            }
              
              
              
	          $order->sign = array();
	          $sign = getsonall('ns_signatures','orderid',$order->e_oid);
	          $order->sign = $sign;                 
                
              
                
              //$tmp211 = getsonall('ns_v1packageitemselect','parentId1',$v21->e_oid);
              //$v21->selects =  array();
              
              //$v21->selects =$tmp211;
            }//end orders
            

            
            //$tmp2->createdDate = SimpleDate::fromStamp($tmp2->createdDate);
            //$tmp2->cancelledDate = SimpleDate::fromStamp($tmp2->cancelledDate);
                    
            
            
            $result->data[] = $tmp2;
        }//end customer

  echo json_encode($result);        
    
 }
 
 /**
  * 
  * myorder
  */
  function myorderfind($action,$condition,$e_oid,$flag='')
  {
	  
	  $result = new stdClass();
	  $result->data = array(); 
	  
	  
	    $sql2 = "SELECT c.e_oid as id, c.* FROM ns_v1myorder as c where 1=1 and  c.e_".$condition." ";
	    
	    $tmp=getall($sql2);
	    
	              $tmp[0]->purchaseItems = array();
	              $pitem = getsonall('ns_v1purchaseitem','order_id',$tmp[0]->e_oid);
	              
	               foreach($pitem as $pis){
	                 $pis->selects = array();//selects
	                 $pis->notes =array();//notes
	                 
	                 $selectarr = getsonall('ns_v1purchaseitemselect','purchaseitem_id',$pis->e_oid);
	                 $notearr = getsonall('ns_v1purchasenote','purchaseitem_id',$pis->e_oid);
	                 
	                 foreach($selectarr as $select){
	                    $pis->selects[] = $select;  
	                    
	                 }
	                 
	                 foreach($notearr as $notes){
	                   $pis->notes[] = $notes;  
	                    
	                 }
	                 
	                 
	                 $tmp[0]->purchaseItems[] = $pis;
	                 
	               }//end purchaseitem
	               
	              $tmp[0]->payments = array();
	              $payment = getsonall('ns_v1payment','orderId',$tmp[0]->e_oid); 
	              $tmp[0]->payments = $payment;
	              
	            
	            $result->data[] = $tmp[0];
	
	  echo json_encode($result);        
      	
  	
  }
  
  /**
   * 
   * findByRequest
   */
  
  function findByRequest($action,$condition,$e_oid,$flag='')
  {
  	
  	  $sql = MiscUtils::getParam('sql', NULL);
      $result = new stdClass();
      $result->data = array(); 
      
        
        $tmp=getall($sql);
        
        if(!empty($tmp))
        {
        	foreach ($tmp as $tmp1)
        	{
        		$result->data[] = $tmp1;
        		
        	}
        	
        }
        
    
      echo json_encode($result);   	
  }
 
 /**
  * 
  * @param unknown_type $action
  * @param unknown_type $condition
  * @param unknown_type $e_oid
  * @param unknown_type $flag
  */
  function  h1purchaseitemfind($action,$condition,$e_oid,$flag='')
  {
  $condition = MiscUtils::getParam('c', 'where 1 = 1'); 
  
  $ordertrackid = MiscUtils::getParam('oid', '0');
  $order = MiscUtils::getParam('o', 'c.operate_date');
  $queue = MiscUtils::getParam('q', 'ASC');
  $page = MiscUtils::getParam('p', START);
  $size = MiscUtils::getParam('s', NULL); 
  $cond = MiscUtils::getParam('cond', '0'); 
  $date = MiscUtils::getParam('date', ''); 
  $from = MiscUtils::getParam('from', ''); 
  $to = MiscUtils::getParam('to', ''); 
  $pageSkip = ($page - 1) * $size;
  
   
  
  $result = new stdClass();
  $subdata = new stdClass();
  
    $sql2 = "SELECT DISTINCT c.e_oid as id, c.* FROM ns_".$action." as c where c.trackId='$ordertrackid' ";
    
    $sql2 .=" and e_oid in (
                        select  min(e_oid) as id from ns_".$action." 
                                                 WHERE trackId='$ordertrackid' 
                                                 group by parent_id,`date`,`price`,photoname,videoname 
                                                 order by id asc) "; 
    
    $sql2 .=  (($order && $queue) ? " ORDER BY $order $queue " : '') ;
    

    $tmp=getall($sql2);
    
    if(empty($tmp))
    {
    	$result->data = array();
    }else{
    
    $subdata->orders = $tmp;
        //foreach($tmp as $tmp2){
            
              //get purchaseitem
              $subdata->purchaseItems = array();

              $sqlpur="select  min(e_oid) as id,parent_id,cancelled,`name`,price,quantity,total from ns_h1purchaseitem WHERE order_id=".$tmp[0]->parent_id." group by parent_id,cancelled,`name`,price,quantity,total order by parent_id desc";
              //$tmppur=getall($sqlpur);
              $idarr = getallid($sqlpur,'id');
              //echo $idstr;
              $purstr = getallid($sqlpur,'parent_id',1);
              
              $sqlpurs ="select  min(pitem_id) AS pitem_id,title,`value`,purchaseitem_id from ns_h1purchaseitemselect  WHERE purchaseitem_id IN ($purstr) AND pitem_id<>0 group by title,`value`,purchaseitem_id order by pitem_id ASC";
              $pitemarr = array_unique(getallid($sqlpurs,'pitem_id') );//去重复
              
              foreach ($pitemarr as $onepitem)
              {
              	if(in_array($onepitem,$idarr))//去重复
              	{
              		continue;
              	}else{//不重复就入栈
              		array_push($idarr,$onepitem);
              	}
              }
              
              //print_r($pitemstr);
              $idstr = getallid($idarr,'','',1);
              
              $cond = "  e_oid in ($idstr) ";
              
              $tmpid = isset($tmp[0]->parent_id)? $tmp[0]->parent_id :NULL;
              $pitem = getsonall('ns_h1purchaseitem','order_id',$tmpid,$cond);

              
              
               foreach($pitem as $pis){
                 $pis->selects = array();//selects
                 
                 $selectarr = getsonall('ns_h1purchaseitemselect','pitem_id',$pis->e_oid);
                 
                 foreach($selectarr as $select){
                    $pis->selects[] = $select;  
                    
                 }
                 
                 $subdata->purchaseItems[] = $pis;            
            
             }
             
             $result->data[] = $subdata;

    }
        //}//end order

  echo json_encode($result);        
  	
  	
  }
 
  function  cuspayment($action,$condition,$e_oid,$flag=''){
  	$orderid = MiscUtils::getParam('orid', '');
  
   
  
    $result = new stdClass();
    $result->data = array(); 
  
    $pathname = 'http://'.DOMAIN .PATH. '/mpdf/emailtemplate.html';
    //$pdfname1 =  file_get_contents($pathname);
    $pdfname =  file_get_contents($pathname);
  
    $sql2 = "SELECT * FROM ns_v1customer where e_oid = ".$e_oid." limit 1";
    $tmp=getone($sql2);
    //echo $sql2;
    
    $paysec = getsecondpayment($orderid);
    //$tmp->paysec = $paysec;
    
			$pdfname = str_replace("[Bride]", $tmp->bridename, $pdfname);
            $pdfname = str_replace("[Groom]", $tmp->groomname, $pdfname);
            $pdfname = str_replace("[XXXX.XX]", $paysec, $pdfname);
                
    //$tmp->emailtmp = $pdfname;
    $result->data[] =$pdfname;//end customer

  echo json_encode($result);        
  }
 
 
 
 
 
 
 
 
 
 
 
 
 

?>